﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OWANotifier.Properties;

namespace OWANotifier
{
    public partial class FormMain : Form
    {
        private bool showBalloon = false;

        public FormMain()
        {
            InitializeComponent();
        }

        public FormMain(bool showBalloon)
        {
            this.showBalloon = showBalloon;
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Notifier.Instance.Poll();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            List<Message> messages = dataGridView1.DataSource as List<Message>;

            System.Diagnostics.Process.Start(messages[dataGridView1.SelectedRows[0].Index].Url);
        }


        private void FormMain_Load(object sender, EventArgs e)
        {
            notifyIcon.Icon = Resources.offline;
            notifyIcon.Text = Application.ProductName;
            notifyIcon.Visible = true;

            notifyIcon.ShowBalloonTip(500, Application.ProductName, Application.ProductName + " is running", ToolTipIcon.Info);

            timer.Interval = Settings.Default.PollInterval * 1000;
            timer.Enabled = true;

            Notifier.Instance.NewMessage += new EventHandler(Notifier_NewMessage);
            Notifier.Instance.PollStarted += new EventHandler(Notifier_PollStarted);
            Notifier.Instance.PollFinished += new EventHandler(Notifier_PollFinished);
            Notifier.Instance.Poll();

            this.Location = new Point(-1000, -1000);
        }

        void Notifier_PollStarted(object sender, EventArgs e)
        {
            notifyIcon.Text = "Checking...";
        }

        void Notifier_PollFinished(object sender, EventArgs e)
        {
            dataGridView1.DataSource = Notifier.Instance.Messages.ToArray();

            if (Notifier.Instance.Status == Notifier.NotifierStatus.Offline)
            {
                notifyIcon.Icon = Resources.offline;
                notifyIcon.Text = "Offline";
            }
            else
            {
                int mcount = Notifier.Instance.Messages.Count;
                notifyIcon.Icon = (mcount > 0) ? Resources.newmail : Resources.nounread;
                notifyIcon.Text = (mcount == 0) ? "No unread messages" :
                            mcount + " unread message" + (mcount > 1 ? "s" : "");
            }

            if (Notifier.Instance.LastError != null)
            {
                notifyIcon.Text = "Error";
                notifyIcon.Icon = Resources.error;
                showNewMessageForm();
            }
        }

        void Notifier_NewMessage(object sender, EventArgs e)
        {
            if (Notifier.Instance.Status == Notifier.NotifierStatus.Offline)
            {
                notifyIcon.Icon = Resources.offline;
                notifyIcon.Text = "Offline";
            }
            else
            {
                notifyIcon.Icon = (Notifier.Instance.Messages.Count > 0) ? Resources.newmail : Resources.nounread;
                notifyIcon.Text = Notifier.Instance.Messages.Count + " unread messages";
            }
            showNewMessageForm();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            if (Notifier.Instance.Status == Notifier.NotifierStatus.Online)
                Notifier.Instance.Poll();
            else if (Notifier.Instance.Status == Notifier.NotifierStatus.Offline)
            {
                notifyIcon.Icon = Resources.offline;
                notifyIcon.Text = "Offline";
            }
        }

        private void FormMain_Shown(object sender, EventArgs e)
        {
            Hide();
        }

        private void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            if ((NewMessageForm.Instance != null) &&
                  ((NewMessageForm.Instance.Visible) &&
                  (!NewMessageForm.Instance.FormToaster.CompletelyClosed)))
            {
                return;
            }
            showNewMessageForm();
        }

        private void showNewMessageForm()
        {
            NewMessageForm nf = NewMessageForm.NewInstance;

            if (Notifier.Instance.Status == Notifier.NotifierStatus.Offline)
            {
                nf.Messages = new List<Message>();
                nf.Messages.Add(new SystemMessage
                {
                    From = "System",
                    Received = DateTime.Now,
                    Subject = "Offline",
                    Unread = false,
                    Severity = SystemMessage.MessageSeverity.Info
                });
            }
            else
            {
                if (Notifier.Instance.Messages.Count > 0)
                {
                    nf.Messages = Notifier.Instance.Messages;
                }
                else
                {
                    nf.Messages = new List<Message>();
                    if (Notifier.Instance.LastError != null)
                    {
                        nf.Messages.Add(new SystemMessage
                        {
                            From = "System",
                            Received = DateTime.Now,
                            Subject = Notifier.Instance.LastError.Message,
                            Unread = false,
                            Exception = Notifier.Instance.LastError,
                            Url = "{Exception}",
                            Severity = SystemMessage.MessageSeverity.Error
                        });
                    }
                    else
                    {
                        nf.Messages.Add(new SystemMessage
                        {
                            From = "System",
                            Received = DateTime.Now,
                            Subject = "No unread messages",
                            Unread = false,
                            Severity = SystemMessage.MessageSeverity.Info
                        });
                    }
                }

            }
            nf.Show();
        }

        private void showToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MouseButtons == MouseButtons.Middle)
            {
                this.CenterToScreen();
                Show();
            }
            else
            {
                string inboxUri = string.Format(new Uri(new Uri(Settings.Default.UnreadMessagesUri), "..").ToString(), OWAMessageListRequest.GetUser(Settings.Default.Username));
                System.Diagnostics.Process.Start(inboxUri.ToString());
            }
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            notifyIcon.Dispose();
            Application.Exit();
        }

        private void checkNowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Notifier.Instance.Status = Notifier.NotifierStatus.Online;
            Notifier.Instance.Poll();
        }

        private void tellMeAgainToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if ((NewMessageForm.Instance != null) &&
              ((NewMessageForm.Instance.Visible) &&
              (!NewMessageForm.Instance.FormToaster.CompletelyClosed)))
            {
                return;
            }
            showNewMessageForm();
        }

        private void goOfflineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Notifier.Instance.Password = null;
            Notifier.Instance.Status = Notifier.NotifierStatus.Offline;
            Settings.Default.Password = null;
            Settings.Default.Save();
            notifyIcon.Icon = Resources.offline;
            notifyIcon.Text = "Offline";
        }

        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (notifyIcon.Icon != null)
                notifyIcon.Visible = false;
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutForm().Show();
        }

        private void composeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string inboxUri = string.Format(new Uri(new Uri(Settings.Default.UnreadMessagesUri), "../Drafts/?Cmd=new").ToString(), OWAMessageListRequest.GetUser(Settings.Default.Username));
            System.Diagnostics.Process.Start(inboxUri.ToString());
        }

        private void animateTime_Tick(object sender, EventArgs e)
        {
            if ((animateTimer.Tag == null) || (((int)animateTimer.Tag) == 0))
                animateTimer.Tag = 1;
            else
                animateTimer.Tag = 0;

            if (Notifier.Instance.Messages.Count > 0)
            {
                notifyIcon.Icon = (((int)animateTimer.Tag) == 0) ? Resources.newmail : Resources.newmail2;
            }
        }
    }
}
